import tkinter as tk
from tkinter import ttk, messagebox, scrolledtext
from datetime import datetime, timedelta
import json
import os

class TimerApp:
    def __init__(self, root):
        self.root = root
        self.root.title("计时工具")
        self.root.geometry("300x350")
        self.root.resizable(True, True)
        
        # 计时相关变量
        self.is_timing = False
        self.start_time = None
        self.end_time = None
        
        # 数据文件
        self.data_file = "timer_records.json"
        
        # 创建界面
        self.create_widgets()
        
        # 加载历史记录
        self.load_records()
        
    def create_widgets(self):
        # 计时显示区域
        self.time_display = tk.Label(self.root, text="00:00:00", font=("Arial", 20))
        self.time_display.pack(pady=2)
        
        # 当前计时信息
        self.current_info = tk.Label(self.root, text="", font=("Arial", 9))
        self.current_info.pack(pady=2)
        
        # 按钮框架
        button_frame = tk.Frame(self.root)
        button_frame.pack(pady=2)
        
        # 开始/停止按钮
        self.toggle_button = tk.Button(button_frame, text="开始", font=("Arial", 10), 
                                     command=self.toggle_timer, width=8)
        self.toggle_button.pack(side=tk.LEFT, padx=2)
        
        # 重置按钮
        self.reset_button = tk.Button(button_frame, text="重置", font=("Arial", 10),
                                    command=self.reset_timer, width=8)
        self.reset_button.pack(side=tk.LEFT, padx=2)
        
        # 查看历史记录按钮
        self.history_button = tk.Button(button_frame, text="历史记录", font=("Arial", 10),
                                      command=self.show_history, width=8)
        self.history_button.pack(side=tk.LEFT, padx=2)
        
        # 状态栏
        self.status_bar = tk.Label(self.root, text="就绪", bd=1, relief=tk.SUNKEN, anchor=tk.W)
        self.status_bar.pack(side=tk.BOTTOM, fill=tk.X)
        
    def toggle_timer(self):
        if not self.is_timing:
            # 开始计时
            self.is_timing = True
            self.start_time = datetime.now()
            self.toggle_button.config(text="停止")
            self.update_display()
            self.current_info.config(text=f"开始: {self.start_time.strftime('%Y-%m-%d %H:%M:%S')}")
            self.status_bar.config(text="正在计时...")
        else:
            # 停止计时
            self.is_timing = False
            self.end_time = datetime.now()
            self.toggle_button.config(text="开始")
            self.current_info.config(text=f"结束: {self.end_time.strftime('%Y-%m-%d %H:%M:%S')}")
            # 自动保存记录
            self.auto_save_record()
            self.status_bar.config(text="计时完成，记录已保存")
            
    def reset_timer(self):
        self.is_timing = False
        self.start_time = None
        self.end_time = None
        self.time_display.config(text="00:00:00")
        self.toggle_button.config(text="开始")
        self.current_info.config(text="")
        self.status_bar.config(text="就绪")
        
    def update_display(self):
        if self.is_timing:
            # 计算经过的时间
            elapsed = datetime.now() - self.start_time
            total_seconds = int(elapsed.total_seconds())
            hours, remainder = divmod(total_seconds, 3600)
            minutes, seconds = divmod(remainder, 60)
            time_str = f"{hours:02d}:{minutes:02d}:{seconds:02d}"
            self.time_display.config(text=time_str)
            self.root.after(1000, self.update_display)  # 每秒更新一次
            
    def auto_save_record(self):
        if self.start_time and self.end_time:
            record = {
                "start": self.start_time.strftime('%Y-%m-%d %H:%M:%S'),
                "end": self.end_time.strftime('%Y-%m-%d %H:%M:%S')
            }
            
            # 添加到记录列表
            self.records.append(record)
            
            # 保存到文件
            self.save_records()
            
    def load_records(self):
        if os.path.exists(self.data_file):
            try:
                with open(self.data_file, 'r', encoding='utf-8') as f:
                    self.records = json.load(f)
            except:
                self.records = []
        else:
            self.records = []
            
    def save_records(self):
        try:
            with open(self.data_file, 'w', encoding='utf-8') as f:
                json.dump(self.records, f, ensure_ascii=False, indent=2)
        except Exception as e:
            messagebox.showerror("保存失败", f"无法保存记录: {str(e)}")
            
    def show_history(self):
        # 如果历史记录窗口已存在，则更新它而不是创建新窗口
        if hasattr(self, 'history_window') and self.history_window and self.history_window.winfo_exists():
            self.history_window.lift()
            self.load_records()  # 重新加载记录
            self.display_records(self.records)  # 更新显示
            return
            
        self.history_window = tk.Toplevel(self.root)
        self.history_window.title("历史记录")
        self.history_window.geometry("550x450")
        self.history_window.minsize(450, 350)
        
        # 创建主框架
        main_frame = tk.Frame(self.history_window)
        main_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
        
        # 筛选框架
        filter_frame = tk.LabelFrame(main_frame, text="筛选记录", padx=5, pady=5)
        filter_frame.pack(fill=tk.X, pady=(0, 10))
        
        # 开始时间筛选
        start_frame = tk.Frame(filter_frame)
        start_frame.pack(fill=tk.X, pady=2)
        tk.Label(start_frame, text="开始时间:").pack(side=tk.LEFT)
        self.start_date_var = tk.StringVar()
        self.start_date_entry = tk.Entry(start_frame, textvariable=self.start_date_var, width=20)
        self.start_date_entry.pack(side=tk.LEFT, padx=5)
        tk.Label(start_frame, text="YYYY-MM-DD HH:MM:SS").pack(side=tk.LEFT)
        
        # 结束时间筛选
        end_frame = tk.Frame(filter_frame)
        end_frame.pack(fill=tk.X, pady=2)
        tk.Label(end_frame, text="结束时间:").pack(side=tk.LEFT)
        self.end_date_var = tk.StringVar()
        self.end_date_entry = tk.Entry(end_frame, textvariable=self.end_date_var, width=20)
        self.end_date_entry.pack(side=tk.LEFT, padx=5)
        tk.Label(end_frame, text="YYYY-MM-DD HH:MM:SS").pack(side=tk.LEFT)
        
        # 筛选和清除按钮
        button_frame = tk.Frame(filter_frame)
        button_frame.pack(fill=tk.X, pady=5)
        tk.Button(button_frame, text="筛选", command=self.filter_records).pack(side=tk.LEFT, padx=5)
        tk.Button(button_frame, text="清除筛选", command=self.clear_filter).pack(side=tk.LEFT, padx=5)
        tk.Button(button_frame, text="删除选中", command=self.delete_selected).pack(side=tk.RIGHT, padx=5)
        tk.Button(button_frame, text="复制选中", command=self.copy_selected).pack(side=tk.RIGHT, padx=5)
        tk.Button(button_frame, text="刷新", command=self.refresh_records).pack(side=tk.RIGHT, padx=5)
        
        # 创建Treeview来显示历史记录
        tree_frame = tk.Frame(main_frame)
        tree_frame.pack(fill=tk.BOTH, expand=True)
        
        # 滚动条
        scrollbar_y = tk.Scrollbar(tree_frame, orient=tk.VERTICAL)
        scrollbar_x = tk.Scrollbar(tree_frame, orient=tk.HORIZONTAL)
        
        # 创建Treeview
        self.records_tree = ttk.Treeview(tree_frame, 
                                         columns=("序号", "开始时间", "结束时间"),
                                         show="headings",
                                         yscrollcommand=scrollbar_y.set,
                                         xscrollcommand=scrollbar_x.set,
                                         selectmode="extended")  # 支持多选
        
        scrollbar_y.config(command=self.records_tree.yview)
        scrollbar_x.config(command=self.records_tree.xview)
        
        # 定义列标题
        self.records_tree.heading("序号", text="序号")
        self.records_tree.heading("开始时间", text="开始时间")
        self.records_tree.heading("结束时间", text="结束时间")
        
        # 设置列宽
        self.records_tree.column("序号", width=40, anchor=tk.CENTER)
        self.records_tree.column("开始时间", width=180, anchor=tk.CENTER)
        self.records_tree.column("结束时间", width=180, anchor=tk.CENTER)
        
        # 布局
        self.records_tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        scrollbar_y.pack(side=tk.RIGHT, fill=tk.Y)
        scrollbar_x.pack(side=tk.BOTTOM, fill=tk.X)
        
        # 加载记录
        self.display_records(self.records)
        
        # 添加关闭按钮
        close_button = tk.Button(main_frame, text="关闭", command=self.history_window.destroy)
        close_button.pack(pady=5)
        
    def display_records(self, records_to_display):
        # 清空现有记录
        for item in self.records_tree.get_children():
            self.records_tree.delete(item)
            
        # 显示记录
        if not records_to_display:
            return
            
        for i, record in enumerate(reversed(records_to_display), 1):
            start_time = record['start']
            end_time = record['end']
            self.records_tree.insert("", tk.END, values=(i, start_time, end_time), tags=(len(records_to_display)-i,))
            
    def filter_records(self):
        start_date_str = self.start_date_var.get().strip()
        end_date_str = self.end_date_var.get().strip()
        
        filtered_records = self.records.copy()
        
        # 根据开始时间筛选（支持精确到秒）
        if start_date_str:
            try:
                # 尝试解析完整的时间格式
                if len(start_date_str) > 10:  # 包含时间部分
                    start_time = datetime.strptime(start_date_str, "%Y-%m-%d %H:%M:%S")
                else:  # 只有日期部分
                    start_time = datetime.strptime(start_date_str, "%Y-%m-%d")
                    
                filtered_records = [r for r in filtered_records 
                                  if datetime.strptime(r['start'], "%Y-%m-%d %H:%M:%S") >= start_time]
            except ValueError:
                messagebox.showerror("错误", "开始时间格式错误，请使用 YYYY-MM-DD 或 YYYY-MM-DD HH:MM:SS 格式")
                return
        
        # 根据结束时间筛选（支持精确到秒）
        if end_date_str:
            try:
                # 尝试解析完整的时间格式
                if len(end_date_str) > 10:  # 包含时间部分
                    end_time = datetime.strptime(end_date_str, "%Y-%m-%d %H:%M:%S")
                else:  # 只有日期部分
                    end_time = datetime.strptime(end_date_str, "%Y-%m-%d") + timedelta(days=1)
                    
                filtered_records = [r for r in filtered_records 
                                  if datetime.strptime(r['start'], "%Y-%m-%d %H:%M:%S") <= end_time]
            except ValueError:
                messagebox.showerror("错误", "结束时间格式错误，请使用 YYYY-MM-DD 或 YYYY-MM-DD HH:MM:SS 格式")
                return
                
        self.display_records(filtered_records)
        
    def clear_filter(self):
        self.start_date_var.set("")
        self.end_date_var.set("")
        self.display_records(self.records)
        
    def delete_selected(self):
        selected_items = self.records_tree.selection()
        if not selected_items:
            messagebox.showwarning("警告", "请先选择要删除的记录")
            return
            
        # 确认删除
        if not messagebox.askyesno("确认删除", "确定要删除选中的记录吗？"):
            return
            
        # 获取选中项的索引
        indices_to_remove = []
        for item in selected_items:
            tags = self.records_tree.item(item, "tags")
            index = int(tags[0])
            indices_to_remove.append(index)
            
        # 从后往前删除，避免索引变化
        indices_to_remove.sort(reverse=True)
        for index in indices_to_remove:
            del self.records[index]
            
        # 重新保存记录
        self.save_records()
        
        # 更新显示
        self.clear_filter()
        self.status_bar.config(text=f"已删除 {len(indices_to_remove)} 条记录")
        
    def copy_selected(self):
        selected_items = self.records_tree.selection()
        if not selected_items:
            messagebox.showwarning("警告", "请先选择要复制的记录")
            return
            
        # 获取选中的记录
        selected_records = []
        for item in selected_items:
            values = self.records_tree.item(item, "values")
            start_time = values[1]
            end_time = values[2]
            selected_records.append((start_time, end_time))
            
        # 按开始时间排序
        selected_records.sort(key=lambda x: datetime.strptime(x[0], "%Y-%m-%d %H:%M:%S"))
        
        # 格式化为指定格式
        copied_text = ""
        for i, (start_time, end_time) in enumerate(selected_records, 1):
            copied_text += f"{i}. {start_time} to {end_time}\n"
            
        # 复制到剪贴板
        self.history_window.clipboard_clear()
        self.history_window.clipboard_append(copied_text.rstrip())  # 去掉最后的换行符
        
        # 显示成功消息
        messagebox.showinfo("复制成功", f"已复制 {len(selected_records)} 条记录到剪贴板")
        
    def refresh_records(self):
        # 重新加载并显示记录
        self.load_records()
        self.display_records(self.records)
        self.status_bar.config(text="记录已刷新")

def main():
    root = tk.Tk()
    app = TimerApp(root)
    root.mainloop()

if __name__ == "__main__":
    main()